package asteroids.statements;


import java.util.*;

import be.kuleuven.cs.som.annotate.Basic;

import asteroids.Ship;
import asteroids.expressions.*;
import asteroids.types.*;

public class IfThenElseStatement extends ComposedStatement {
	
	private Expression condition;
	private Statement then;
	private Statement otherwise;

	public IfThenElseStatement(int line, int column, Expression condition, Statement then, Statement otherwise) {
		super(line, column);
		this.condition = condition;
		this.then = then;
		this.otherwise = otherwise;
	}

	@Basic
	public Expression getCondition() {
		return condition;
	}
	
	@Basic
	public Statement getIfLoop() {
		return then;
	}

	@Basic
	public Statement getElseLoop() {
		return otherwise;
	}

	@Override
	public int getNbOfStatements() {
		//Only one statement will be executed.
		return 1;
	}

	@Override
	public Statement getStatementAt(int index) throws IndexOutOfBoundsException {
		if ((index != 1) && (index != 2))
			throw new IndexOutOfBoundsException();
		if (index == 1)
			return getIfLoop();
		else
			return getElseLoop();
	}

	@Override
	public void execute(Ship ship) {
		if(((BooleanType) getCondition().evaluate(ship, ship.getProgram().getGlobals())).getValue()) 
			getIfLoop().execute(ship);
		else
			getElseLoop().execute(ship);
	}
	
	@Override
	public List<String> getTypeCheckErrors(List<String> typeErrors,	Map<String, Type> globalVariables) {
		typeErrors = getCondition().getTypeCheckErrorsExpressions(typeErrors, globalVariables);
		if(getCondition().evaluate(null, globalVariables).getClass() != BooleanType.class)
			typeErrors.add("Line: " + getLine() + " Column: " + getColumn() + " - The condition '" + getCondition().toString() + "' is expected to be from the type 'boolean'.");
		typeErrors = getIfLoop().getTypeCheckErrors(typeErrors, globalVariables);
		typeErrors = getElseLoop().getTypeCheckErrors(typeErrors, globalVariables);
		return typeErrors;
	}
	
}
